package com.cuit.dashboard.system.controller;

import com.cuit.dashboard.common.util.Result;
import com.cuit.dashboard.system.entity.SysOssEntity;
import com.cuit.dashboard.system.service.SysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @program: zuke
 * @description: 阿里云OSS实现文件上传
 * @author: KamTang
 * @create: 2022-06-11 18:55
 **/
@RestController
@RequestMapping("/sys/oss")
public class OssController {

    @Autowired
    private SysOssService ossService;


    @GetMapping("/policy")
    public Result getPolicy () {
        Map<String, String> policy = ossService.getPolicy();
        return Result.ok().put("data", policy);
    }



    /**
     * 列表
     * @param params
     * @return
     */
    @GetMapping("/list")
    public Result list (@RequestParam Map<String, Object> params) {
        return Result.ok().put("page", ossService.queryPage(params));
    }

    /**
     * 添加
     */
    @PostMapping("/add")
    public Result add (@RequestBody SysOssEntity oss) {
        boolean flag = ossService.save(oss);
        if (flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 删除DB中的图片链接
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    public Result deleteBatch(@RequestBody Long[] ids) {
        boolean flag = ossService.removeByIds(Arrays.asList(ids));
        if (flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 上传图片至oss
     * @param file
     * @return
     */
    @PostMapping("/uploadImgFile")
    public Result uploadImgFile(MultipartFile file){
        String s = ossService.upload(file);
        return Result.ok().put("url",s);
    }

    /**
     * 删除单个图片文件
     * @param file
     * @return
     */
    @PostMapping("/deleteImgFile")
    public Result deleteImgFile(String file){
        //https://xinguan-parent.oss-cn-hangzhou.aliyuncs.com/2020/10/20/300f7c9d6546486eb55d825d4edcf668.png
        try {
            String[] split = file.split(".com/");
            ossService.deleteFile(split[1]);
            return Result.ok();
        }catch (Exception e){
            //需要打印错误日志到本地系统中(服务器系统)
            return Result.error();
        }
    }

    /**
     * 批量删除多个图片文件
     * @param file
     * @return
     */
    @PostMapping("/deleteUnNeedImg")
    public Result deleteBatch(@RequestBody List<String> file) {
        try {
            ossService.deleteBatch(file);
            return Result.ok();
        } catch (Exception e){
            return Result.error();
        }
    }

}
